<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展 
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------

namespace app\admin\controller\wddj;

use app\admin\model\wddj\Payments;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\wddj\Order
     */
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wddj\Order;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("paidList", $this->model->getPaidList());
        $this->view->assign("payMethodList", $this->model->getPayMethodList());
        $this->view->assign("stateList", $this->model->getStateList());
        $sound_recording_status = (new \app\admin\model\wddj\Config())->where('id',1)->value('sound_recording_status');
        $this->assignconfig('sound_recording_status',$sound_recording_status);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $wechat_id = $this->request->get('wechat_id');
            if (!empty($wechat_id)) {
                $this->model = $this->model->where('wechat_id',$wechat_id);
            }

            $list = $this->model
                    ->where('state','<>','unpaid')
                    ->where($where)
                    ->with(['agent'])
                    ->order($sort, $order)
                    ->paginate($limit);

            $paymentModel = new Payments();
            foreach ($list as &$row) {
                $row->passenger = \app\admin\model\wddj\Order::getPassenger($row);
                if (empty($row->actual_duration)) {
                    $row->actual_duration = '-';
                } else {
                    $seconds = bcdiv($row->actual_duration,60,2);
                    $row->actual_duration = ceil($seconds);
                }
                $paymentObj = $paymentModel
                    ->where('order_id',$row->id)
                    ->where('payment_type','prepaid')
                    ->where('payment_status','completed')
                    ->find();
                if ($row['state'] != 'completed' && $paymentObj) {
                    $row->refund_show_status = 1;
                } else {
                    $row->refund_show_status = 2;
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * Desc 详情
     * Create on 2024/10/26 17:23
     * Create by wangyafang
     */
    public function details($ids = null)
    {
        $row = $this->model->get($ids);
        $row->passenger = \app\admin\model\wddj\Order::getPassenger($row);
        $row['start_itinerary_take_pictures'] = explode(',',$row['start_itinerary_take_pictures']);
        $row['arrive_at_take_pictures'] = explode(',',$row['arrive_at_take_pictures']);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * Desc 行程路线
     * Create on 2024/11/8 9:12
     * Create by wangyafang
     */
    public function travel_itinerary($ids = null)
    {
        $row = $this->model->get($ids);
        $tencent_map_web_service_key = (new \app\admin\model\wddj\Config())->where('id',1)->value('tencent_map_web_service_key');

        $from_address = $row['from_address'];
        $fromcoord = $row['from_lng'].','.$row['from_lat'];
        $to_address = $row['to_address'];
        $tocoord = $row['to_lng'].','.$row['to_lat'];

        $url = "https://map.qq.com/?from=$from_address&fromcoord=$fromcoord&ref=$tencent_map_web_service_key&tactic=1&to=$to_address&tocoord=$tocoord&type=nav";
        $this->view->assign('url', $url);
        return $this->view->fetch();
    }

    public function add()
    {
        return;
    }

    public function multi($ids = null)
    {
        return;
    }

    public function del($ids = null)
    {
        return;
    }

    public function edit($ids = null)
    {
        return;
    }

    /*
     * 同意退款
     */
    public function agree_refund($ids=null){
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $paymentObj = (new Payments())
            ->where('order_id',$ids)
            ->where('payment_type','prepaid')
            ->where('payment_status','completed')
            ->find();
        if(!$paymentObj){
            $this->error('退款信息不存在');
        }
        $orderObj = $this->model->get($ids);
        if (!$orderObj) {
            $this->error('订单信息不存在');
        }

        $refund_no = wddj_create_order();

        $res= \addons\wddj\library\Wxapp::payRefund($orderObj->order_no,$refund_no,$paymentObj->pay_amount,array('refund_desc'=>'后台退款'));
        if($res && $res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            $result = false;
            Db::startTrans();
            try {
                $paymentObj->payment_status = 'refunded';
                $result = $paymentObj->save();
                $orderObj->state = 'cancelled';
                $orderObj->save();
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error(__('No rows were inserted'));
            }
            $this->success('退款操作成功');
        }else{
            $this->error('退款失败,错误信息：'.$res['return_msg']);
        }
    }

}
